package com.atguigu.tingshu.account.receiver;


import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Component
@Slf4j
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private RechargeInfoService rechargeInfoService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_RECHARGE_PAY_SUCCESS,durable="true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_RECHARGE_PAY_SUCCESS
    ))
    public void rechargePaySuccess(String orderNo,Message message,Channel channel){
        try {
            if (!StringUtils.isEmpty(orderNo)){
                rechargeInfoService.rechargePaySuccess(orderNo);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //  bindings: 1. 在服务器内部实现队列与交换机的绑定关系!
    //  queues: 1. 当对于与交换机有绑定关系时，直接还用queues;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable="true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void register(Long userId, Message message, Channel channel){
        System.out.println(("用户注册成功！" + userId));
        //消息在哪？
        byte[] body = message.getBody();
        System.out.println(("消息内容：\t" + new String(body).toString()));
        System.out.println("Your消息内容：\t" + message.getMessageProperties().getDeliveryTag());

        try {
            //判断
            if (null != userId){
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            //消费异常
            System.out.println(e.getMessage());
            log.error(e.getMessage());
        }
        //手动确认消息，保证消息从队列中出队，否则会造成消息积压，表示是否批量签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
